package com.itboye.textileexpes.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.itboye.textileexpes.beans.ShopCarBeanCopy;
import com.itboye.textileexpes.beans.ShopCarBeanCopy.GetList;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseFragment;
import com.itboye.textileexpres.login.LoginActivity;

/**
 * ���ﳵFragment
 * 
 * @author dsawe
 * 
 */
public class ShopCartFragment extends BaseFragment implements Observer,
		OnClickListener {

	// ShopCarBeanCopy dataList = new ShopCarBeanCopy();
	// ShopCarAdapter adapter;
	ListView xlistView;
	private int pageNum = 1;
	ViewGroup selectedAll;
	TextView delete;
	View back;
	String p;
	// ShopCarPresenter carPresenter;
	TextView heji;
	View jiesuan;
	int count = 0;
	Button btn_login;// �c�����o
	// ArrayList<String> ids = new ArrayList<String>();// ��ѡɾ��
	private String uid;

	private TextView tvtextNumber;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_shop_car;

	}

	@Override
	public void onMyActivityCreated() {
		showProgressDialog("���ݼ����У����Ժ�", true);
		// IntentFilter filter = new IntentFilter("changeshopcart");
		// getActivity().registerReceiver(broadcastReceiver, filter);
		mAdapter = new AppAdapter(getActivity(), this);
		xlistView.setAdapter(mAdapter);
		tvtextNumber.setText(mAdapter.getItem(20) + "");
		xlistView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// Intent intent=new
				// Intent(getActivity(),GoodsDetailFragmentActivity.class);
				// intent.putExtra("pid",
				// dataList.getList().get(arg2).getP_id());
				// startActivity(intent);
			}
		});
		// uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID,
		// "");
		// if (uid == "" || uid == null) {
		// setInvisible();
		// } else {
		// setVisible();
		// }

		// step 1. create a MenuCreator
		// SwipeMenuCreator creator = new SwipeMenuCreator() {
		//
		// @Override
		// public void create(SwipeMenu menu) {
		//
		// SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
		// deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
		// 0x3F, 0x25)));
		// deleteItem.setTitle("ɾ��");
		// deleteItem.setTitleColor(Color.WHITE);
		// // // set item width
		// deleteItem.setWidth(dp2px(90));
		// deleteItem.setTitleSize(18);
		// // // set a icon
		// // deleteItem.setIcon(R.drawable.ic_delete);
		// // deleteItem.setBackground(R.drawable.delete_list_item_bg);
		// // add to menu
		// menu.addMenuItem(deleteItem);
		// }
		// };
		// set creator
		// xlistView.setMenuCreator(creator);
		// step 2. listener item click event
		// xlistView.setOnMenuItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		// xlistView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
		// @Override
		// public void onMenuItemClick(int position, SwipeMenu menu, int index)
		// {
		//
		// switch (index) {
		// case 0:
		// ShopCarBean model = new ShopCarBean();
		// model.setId(dataList.getList().get(position).getId());
		// // carPresenter.delete(model);
		//
		// // open
		// // open(item);
		// break;
		// case 1:
		//
		// break;
		// }
		// }
		// });
		// carPresenter = new ShopCarPresenter(this);
		// carPresenter.getShopcar(uid);
		setListener();
	}

	// BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
	//
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// uid=(String) SPUtils.get(getContext(), null, SpPublicParams.UID,
	// "");
	// carPresenter.getShopcar(uid);
	// }
	// };
	private AppAdapter mAdapter;
	private ArrayList<GetList> arrayDataList;

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	public void calculatePrice() {
		double sum = 0;
		int count = 0;
		// z
		// for (ShopCarBeanCopy.GetList bean : dataList.getList()) {
		// if (bean.isSelected()) {
		// count++;
		// sum = sum + IntegerParse.parse(bean.getCount(), 0)
		// * DoubleParse.parse(bean.getPrice(), 0);
		// }
		// }
		p = String.format("%.2f", sum);
		heji.setText("��" + p);
		heji.setTag(p);
		// if (count == dataList.getList().size() && count != 0) {

		if (count != 0) {
			selectedAll.setSelected(true);

		} else {
			selectedAll.setSelected(false);

		}

	}

	public void setVisible() {
		getView().findViewById(R.id.btn_login).setVisibility(View.GONE);
		getView().findViewById(R.id.delete).setVisibility(View.VISIBLE);
		getView().findViewById(R.id.selectedAll).setVisibility(View.VISIBLE);
		xlistView.setVisibility(View.VISIBLE);
		getView().findViewById(R.id.bottomBar).setVisibility(View.VISIBLE);
	}

	public void setInvisible() {
		getView().findViewById(R.id.btn_login).setVisibility(View.VISIBLE);
		getView().findViewById(R.id.delete).setVisibility(View.GONE);
		getView().findViewById(R.id.selectedAll).setVisibility(View.GONE);
		xlistView.setVisibility(View.GONE);
		getView().findViewById(R.id.bottomBar).setVisibility(View.GONE);
	}

	private void setListener() {
		// TODO Auto-generated method stub
		selectedAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				v.setSelected(!v.isSelected());
				if (v.isSelected()) {
					v.setSelected(true);
					// for (ShopCarBeanCopy.GetList bean : dataList.getList()) {
					// bean.setSelected(true);
					// }
				} else {
					v.setSelected(false);
					// for (ShopCarBeanCopy.GetList bean : dataList.getList()) {
					//
					// bean.setSelected(false);
					// }
				}

				notifySelectedViewState(v.isSelected());
				calculatePrice();
			}
		});

		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				List<String> selectIds = new ArrayList<String>();
				// for (ShopCarBeanCopy.GetList bean : dataList.getList()) {
				// if (bean.isSelected()) {
				// selectIds.add(bean.getId());
				// }
				// }
				if (selectIds.size() == 0) {
					toast("Ո���x����Ҫ�Ƴ�����Ʒ");
					return;
				}
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append(selectIds.get(0));
				// for (int i = 1; i < selectIds.size(); i++) {
				// stringBuilder.append(",").append(selectIds.get(i));
				// }
				// carPresenter.deleteShopcar(stringBuilder);
			}
		});
	}

	protected void notifySelectedViewState(boolean b) {
		int count = xlistView.getChildCount();
		for (int i = 0; i < count; i++) {
			try {
				View v = xlistView.getChildAt(i).findViewById(R.id.isSelected);
				v.setSelected(b);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	protected void queryCountAndBuy() {
		List<String> ids = new ArrayList<String>();
		List<String> counts = new ArrayList<String>();
		// for (ShopCarBeanCopy.GetList bean : dataList.getList()) {
		// ids.add(bean.getId());
		// counts.add(bean.getCount());
		// }

		// ��ȡ�б����ж�����Ʒ
		int count = xlistView.getChildCount();
		// �б����Ƿ���ѡ�е���Ʒ�ı��λ
		boolean selectOrNot = false;
		// ����forѭ���鿴��Ʒ�Ƿ�ѡ�е�״̬
		for (int i = 0; i < count; i++) {
			try {
				View v = xlistView.getChildAt(i).findViewById(R.id.isSelected);
				if (v.isSelected()) {
					// ����б�ѡ�еı��λ�ĳ�true��
					selectOrNot = true;
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// ture����ѡ�� false ��ѡ�У�
		if (!selectOrNot) {
			// ��ѡ����˾
			toast("��ѡ���ﳵ");
			return;
		}

		StringBuilder idsBuilder = new StringBuilder();
		StringBuilder countsBuilder = new StringBuilder();

		if (ids.size() > 0) {
			idsBuilder.append(ids.get(0));
			countsBuilder.append(counts.get(0));
		}

		for (int i = 1; i < ids.size(); i++) {
			idsBuilder.append(",").append(ids.get(i));
			countsBuilder.append(",").append(counts.get(i));
		}
		// ArrayList<GetList> arrayList = new ArrayList<GetList>();
		// for (int i = 0; i < dataList.getList().size(); i++) {
		// if (dataList.getList().get(i).isSelected()) {
		// arrayList.add(dataList.getList().get(i));
		// }
		// }
		// if (arrayList.size() <= 0) {
		// ByAlert.alert("��ѡ���ﳵ");
		// return;
		// }
		// Intent intent=new Intent(getActivity(),QueRenDingDan.class);
		// intent.putExtra("list", arrayList);
		// intent.putExtra("price", heji.getText().toString());
		// startActivity(intent);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable arg0, Object date) {
		// dataList = new ShopCarBeanCopy();
		// ResultEntity entity = handlerError(date);
		// ByAlert.alert(entity.getData() + "");
		// try {
		// dataList = (ShopCarBeanCopy) entity.getData();
		// } catch (Exception e) {
		//
		// }

		// if (entity.getEventType() == ShopCarPresenter.ShopCar_success) {
		// if (dataList.getList() != null ) {
		// setVisible();
		// arrayDataList=dataList.getList();
		// mAdapter = new AppAdapter(getActivity(),dataList.getList(),this);
		// xlistView.setAdapter(mAdapter);
		// }
		// } else if (entity.getEventType() ==
		// ShopCarPresenter.ShopCarFailEvent) {
		// ByAlert.alert("���ﳵ��ʱû�ж���");
		// } else if (entity.getEventType() ==
		// ShopCarPresenter.ShopCarDelete_success) {
		//
		// ByAlert.alert(entity.getData() + ">>>");
		// carPresenter.getShopcar(uid);
		// } else if (entity.getEventType() ==
		// ShopCarPresenter.ShopCarDeleteFailEvent) {
		// ByAlert.alert("ɾ��ʧ��");
		// } else {
		// ByAlert.alert(entity.getData() + "");
		// }
		// try {
		// closeProgressDialog();
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		// }
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.btn_login:
			getActivity().startActivity(
					new Intent(getActivity(), LoginActivity.class));
			break;
		case R.id.jiesuan:
			queryCountAndBuy();

			break;
		default:
			break;
		}

	}

	class AppAdapter extends BaseAdapter {
		Context context;
		// ArrayList<ShopCarBeanCopy.GetList> list;
		ShopCartFragment shopCarFragment;

		public AppAdapter(Context context,

		ShopCartFragment shopCarFragment) {
			this.context = context;
			// this.list = list;
			this.shopCarFragment = shopCarFragment;
		}

		@Override
		public int getCount() {
			return 20;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = View.inflate(getActivity()
						.getApplicationContext(), R.layout.item_shop_car, null);
				holder = new ViewHolder();
				holder.isSelected = convertView.findViewById(R.id.isSelected);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.img = (ImageView) convertView.findViewById(R.id.img);
				holder.guige = (TextView) convertView.findViewById(R.id.guige);
				// holder.jiage = (TextView) convertView
				// .findViewById(R.id.txtPerce);
				// holder.jia = (TextView) convertView.findViewById(R.id.jia);
				//
				// holder.jian = (TextView) convertView.findViewById(R.id.jian);
				// holder.input = (TextView)
				// convertView.findViewById(R.id.input);
				holder.isSelected.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						int posi = (Integer) v.getTag();
						// ShopCarBeanCopy.GetList bean = list.get(posi);

						// bean.setSelected(!bean.isSelected());
						// if (bean.isSelected()) {
						// v.setSelected(true);
						// } else {
						// v.setSelected(false);
						// }
						// shopCarFragment.calculatePrice();
					}
				});

				// holder.jia.setOnClickListener(new OnClickListener() {
				//
				// @Override
				// public void onClick(View v) {
				// int posi = (Integer) v.getTag();
				// TextView editText = (TextView) ((ViewGroup) v
				// .getParent()).getChildAt(1);
				// // int count = IntegerParse.parse(list.get(posi)
				// // .getCount(), 0);
				// count++;
				// editText.setText(count + "");
				// // list.get(posi).setCount(count + "");
				// shopCarFragment.calculatePrice();
				//
				// }
				// });
				//
				// holder.jian.setOnClickListener(new OnClickListener() {
				//
				// @Override
				// public void onClick(View v) {
				// int posi = (Integer) v.getTag();
				// TextView editText = (TextView) ((ViewGroup) v
				// .getParent()).getChildAt(1);
				// // int count = IntegerParse.parse(list.get(posi)
				// // .getCount(), 0);
				// count--;
				// if (count < 1) {
				// count = 1;
				// }
				// editText.setText(count + "");
				// // list.get(posi).setCount(count + "");
				// shopCarFragment.calculatePrice();
				// }
				// });
				convertView.setTag(holder);
			} else {

				holder = (ViewHolder) convertView.getTag();
			}
			// ShopCarBeanCopy.GetList shopCarBean = list.get(position);
			// System.out.println("���" + shopCarBean.getSku_desc());
			// holder.name.setText(shopCarBean.getName());
			// holder.guige.setText(shopCarBean.getSku_desc());
			// holder.jiage.setText(shopCarBean.getPrice());
			// holder.swipe.setText("ɾ��");
			// �����±�
			holder.isSelected.setTag(position);

			// if (shopCarBean.isSelected()) {
			// holder.isSelected.setSelected(true);
			// } else {
			// holder.isSelected.setSelected(false);
			// }
			// holder.input.setText(shopCarBean.getCount() + "");
			// XImageLoader.load(list.get(position).getIcon_url(), holder.img);
			// holder.jia.setTag(position);
			// holder.jian.setTag(position);
			// holder.input.setTag(position);
			// holder.iv_icon.setImageDrawable(item.loadIcon(getActivity().getPackageManager()));
			// holder.tv_name.setText(item.loadLabel(getActivity().getPackageManager()));
			return convertView;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		class ViewHolder {
			View isSelected;
			TextView name;
			Button swipe;
			ImageView img;
			TextView guige;
			// TextView jiage;
			// TextView jia;
			// TextView jian;
			// TextView input;
			TextView txtPerce;

		}
	}
}
